﻿namespace Away.Jobs.Repositories.Models;

public class MapProfile : Profile
{
    public MapProfile()
    {
        CreateMap<QrtzJobDetail, JobDetail>()
            .ForMember(d => d.JobData, opt => opt.ConvertUsing(new BytesToString(), src => src.JobData));
        CreateMap<JobDetail, QrtzJobDetail>()
            .ForMember(d => d.JobData, opt => opt.ConvertUsing(new StringToBytes()!, src => src.JobData));
        CreateMap<QrtzTrigger, TriggerModel>()
            .ForMember(d => d.JobData, opt => opt.ConvertUsing(new BytesToString(), src => src.JobData));
        CreateMap<QrtzBlobTrigger, BlobTriggerModel>()
            .ForMember(d => d.BlobData, opt => opt.ConvertUsing(new BytesToString(), src => src.BlobData));
        CreateMap<QrtzCronTrigger, CronTriggerModel>();
        CreateMap<QrtzSimpleTrigger, SimpleTriggerModel>();
        CreateMap<QrtzSimpropTrigger, SimpropTriggerModel>();
    }
    private class BytesToString : IValueConverter<byte[]?, string>
    {
        public string Convert(byte[]? sourceMember, ResolutionContext context)
        {
            if (sourceMember == null)
            {
                return string.Empty;
            }
            return System.Text.Encoding.UTF8.GetString(sourceMember);
        }
    }
    private class StringToBytes : IValueConverter<string, byte[]?>
    {
        public byte[]? Convert(string sourceMember, ResolutionContext context)
        {
            if (string.IsNullOrWhiteSpace(sourceMember))
            {
                return null;
            }

            return System.Text.Encoding.Default.GetBytes(sourceMember);
        }
    }
}
